import axios from 'axios'
import { getToken, removeToken } from './auth'

const API = axios.create({
  baseURL: 'http://127.0.0.1:8080'
})

// 拦截器
API.interceptors.request.use(function (config) {
  const { url } = config
  
  if(url.startsWith('/user') && !url.startsWith('/user/login') && !url.startsWith('/user/registered')) {
    config.headers.common['authorization'] = getToken()
  }
  
  return config
})

API.interceptors.response.use(response => {
  const { status } = response.data
  if (status === 400) {
    // 此时，说明 token 失效，直接移除 token 即可
    removeToken()
  }
  return response
})

export {API}
